const { bookAPI } = require('../../utils/api.js');

Page({
  data: {
    imagePath: '',
    isbn: ''
  },

  onLoad(options) {
    if (options && options.img) {
      let img = options.img;
      try { img = decodeURIComponent(img); } catch (_) {}
      this.setData({ imagePath: img });
    }
  },

  goBack() {
    wx.navigateBack();
  },

  onIsbnInput(e) {
    this.setData({ isbn: e.detail.value });
  },

  pasteIsbn() {
    if (wx.getClipboardData) {
      wx.getClipboardData({
        success: (res) => {
          const txt = (res && res.data) ? String(res.data) : '';
          const isbn13 = (txt.match(/\d{13}/) || [])[0] || txt;
          this.setData({ isbn: isbn13 });
        }
      });
    }
  },

  clearIsbn() {
    this.setData({ isbn: '' });
  },

  chooseImage() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['camera','album'],
      success: (res) => {
        const file = res.tempFiles && res.tempFiles[0];
        if (file) {
          this.setData({ imagePath: file.tempFilePath });
        }
      }
    });
  },

  onSubmit() {
    const raw = (this.data.isbn || '').trim();
    const isbn13 = (raw.match(/\d{13}/) || [])[0];
    if (!isbn13 || !(isbn13.startsWith('978') || isbn13.startsWith('979'))) {
      wx.showToast({ title: '请输入以978/979开头的13位ISBN', icon: 'none' });
      return;
    }
    wx.showLoading({ title: '查询中...', mask: true });
    bookAPI.getByIsbn(isbn13)
      .then((resp) => {
        wx.hideLoading();
        if (resp && resp.code === 200 && resp.data) {
          // 跳转到新的书籍详情页并传递数据
          wx.navigateTo({
            url: `/pages/book-info/book-info?isbn=${isbn13}`,
            success: (navRes) => {
              const channel = navRes.eventChannel;
              if (channel && channel.emit) {
                channel.emit('bookData', { book: resp.data, imagePath: this.data.imagePath });
              }
            }
          });
        } else {
          wx.showToast({ title: (resp && resp.message) || '未找到图书', icon: 'none' });
        }
      })
      .catch((err) => {
        wx.hideLoading();
        const msg = err && err.message ? err.message : '查询失败';
        wx.showToast({ title: msg, icon: 'none' });
      });
  }
});